import updateManager from "./utils/updateManager"
import { baseUrl } from "./api/request"
import { ApigetUsePatient } from "./api/index"
import Scoket from "./api/scoket"
import EventEmitter from "./utils/event"; // 事件总线
App({
  onLaunch() {
    updateManager()
  },
  onShow() {
    this.setWebScoket()
  },
  onHide() {
    // setTimeout(_=>{
    //   if(this.ws && this.ws.close) this.ws.close()
    // },500)
  },
  globalData: {
    userInfo: null,
    $baseUrl: baseUrl,
    $path: baseUrl + "/storage/upload/",
    isClose: true
    
  },
  event: new EventEmitter(),
  ws: null,
  
  setWebScoket(){
    if(this.globalData.isClose) {
      if( this.ws && this.ws.close) this.ws.close()
      this.ws = new Scoket()
    }
  },

  setWsIsClose(flag) {
    this.globalData.isClose = flag
  },

  setPath(url,flag=false) {
    if(url) {
      return this.globalData.$path + url
    }
    if(flag) {
      return "/assets/common/医生.png"
    }
    return ""
  },

  isToken(){
    return !!wx.getStorageSync('token')
  },

  isLogin(){
    return new Promise((resolve,reject) => {
      if(this.isToken()){
        resolve()
      }else {
        let pages = getCurrentPages() //获取加载的页面
        let path = pages[pages.length - 1]
        let url = ''
        let query = ""
        query = objectConvertToQuery(path.options)
        url = `/${path.route}${query}`
        wx.setStorageSync('fromUrl', url)
        wx.navigateTo({
          url: '/pages/login/index',
        })
        reject()
      }
    })
  },
  
  setUserInfo(options){
    this.globalData.userInfo = options
    wx.setStorageSync('userInfo', options)
  },

  async getUserInfo(){
    if(!this.globalData.userInfo) {
      let data = wx.getStorageSync('userInfo')
      // if(!data) {
      //   const res = await ApigetUsePatient()
      //   data = res.data
      //   wx.setStorage({
      //     key:"userInfo",
      //     data
      //   })
      // }
      this.globalData.userInfo = data
    }
    return Promise.resolve(this.globalData.userInfo) 
  },
})
